package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.SupplierIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.session.ServerSessionUser;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.Supplier;
import com.wh.wisdomsite.xbox.st.service.ISupplierService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 供应商信息Controller
 *
 * @author 蔡道行
 * @version V1.0
 * @date 15:16 2018/12/24
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 */
@Controller
@RequestMapping("/supplier")
public class SupplierController {

    private static final Log logger = LogFactory.getLog(SupplierController.class);

    @Autowired
    private ISupplierService iSupplierService;

    /**
     * 跳转到供应商页面
     *
     * @return
     */
    @RequiresPermissions("rules:st_supplier_page")
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return "st/supplier/supplierList";
    }

    /**
     * 获取供应商列表
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_supplier_find")
    @RequestMapping(value = "/supplierList.do")
    public void supplierList(HttpServletResponse response, SupplierIn in) {
        try {
            logger.info("加载供应商列表-->>开始");
            logger.info("加载供应商列表-->>开始-->>" + in.getPage());
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Supplier> page = new Page<>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Supplier> ewSupplier = new EntityWrapper<Supplier>();
            ewSupplier.setEntity(new Supplier());
            Boolean isAdmin = UserUtils.isSysAdmin();
            //若不是管理员则添加查询条件
            if(!isAdmin){
                ewSupplier = setEntityWrapper(ewSupplier, "co");
            }
            if (StringUtils.isNotEmpty(in.getSupName())) {
                ewSupplier.like("supName", in.getSupName());
            }
            if (StringUtils.isNotEmpty(in.getSocialCode())) {
                ewSupplier.like("socialCode", in.getSocialCode());
            }
            ewSupplier.orderBy("createDate", true);
            Page<Map<String, Object>> supplierPage = iSupplierService.getMapsPage(page, ewSupplier);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (supplierPage.getRecords().size() > 0) {
                for (Map<String, Object> supplier : supplierPage.getRecords()) {
                    JSONObject object = new JSONObject(supplier);
                    object.put("id", supplier.get("id"));
                    array.put(object);
                }
            }
            json.put("total", supplierPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载供应商列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 供应商详情
     *
     * @param in
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_supplier_view")
    @RequestMapping("supplierDesc.do")
    public String supplierDescDetails(SupplierIn in, HttpServletRequest request) {
        logger.info("供应商详情-->>开始");
        final Map<String, Object> supplier = iSupplierService.getMapById(in.getId());
        if (null != supplier.get("createBy")) {
            supplier.put("createBy", UserMapManager.getUserLoginNameInMap(supplier.get("createBy").toString()));
        }
        if (null != supplier.get("updateBy")) {
            supplier.put("updateBy", UserMapManager.getUserLoginNameInMap(supplier.get("updateBy").toString()));
        }
        request.setAttribute("supplier", supplier);
        logger.info("供应商详情-->>结束");
        return "st/supplier/supplierDesc";
    }

    /**
     * 删除供应商
     * @param supId
     * @param response
     */
    @RequiresPermissions("rules:st_supplier_del")
    @RequestMapping(value = "del.do", method = RequestMethod.GET)
    public void del(String supId, HttpServletResponse response) {
        try {
            logger.info("删除供应商-->>开始");
            iSupplierService.deleteById(supId);
            logger.info("删除供应商-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除供应商-->>Exception" + e.getMessage());
        }
    }


    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toSupplier.do")
    public ModelAndView toAddSupplier(String supId, HttpServletRequest request) {
        logger.info("添加修改供应商跳转-->>开始");
        Map<String, Object> supplier = null;
        if (StringUtils.isNotEmpty(supId)) {
            supplier = iSupplierService.getMapById(supId);
            request.setAttribute("supplier", supplier);
        }
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        Supplier supplier1 = new Supplier();
        supplier1.setCompanyId(companyId);
        request.setAttribute("DefaultCompany", companyId);
        logger.info("添加修改供应商跳转-->>开始");
        return new ModelAndView("st/supplier/supplierOption");
    }

    /**
     * 更新或修改供应商
     *
     * @param supplier
     * @param response
     */
    @RequiresPermissions("rules:st_supplier_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Supplier supplier, HttpServletResponse response) {
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        //查看供应商是否已经存在
        try {
            if (StringUtils.isNotEmpty(supplier.getSupId())) {
                logger.info("修改供应商-->>开始");
                supplier.setUpdateDate(new Date());
                supplier.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                iSupplierService.updateById(supplier);
                System.out.println("完毕");
                logger.info("修改供应商-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("更新供应商成功"));
            } else {
                logger.info("添加供应商-->>开始");
                supplier.setCreateBy(UserUtils.getCurrentUser().getUsId());
                supplier.setCreateDate(new Date());
                supplier.setCompanyId(companyId);
                iSupplierService.insert(supplier);
                logger.info("添加供应商-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("添加供应商成功"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加修改供应商-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取供应商列表
     * @param response
     * @param companyId
     */
    @RequestMapping(value = "/getSupplierList.do")
    public void getSupplierList(HttpServletResponse response, String companyId) {
        List<Supplier> supplierList = new ArrayList<Supplier>();
        try {
            logger.info("获取供应商列表-->>开始");
            EntityWrapper<Supplier> ewSupplier = new EntityWrapper<Supplier>();
            ewSupplier.setEntity(new Supplier());
            if(!UserUtils.isSysAdmin()){
                if (StringUtils.isNotEmpty(companyId)) {
                    ewSupplier.eq("companyId", companyId);
                }
            }
            ewSupplier.groupBy("createDate");
            supplierList = iSupplierService.selectList(ewSupplier);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取供应商列表-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(supplierList));
        logger.info("获取供应商列表-->>结束");
    }



    /**
     * 根据权限设置查询范围
     * @param ew
     * @param companyTableAlias
     * @return
     */
    public EntityWrapper setEntityWrapper(EntityWrapper ew, String companyTableAlias) {
        ServerSessionUser serverSessionUser = UserUtils.getServerSessionUser();
        String dataScope = serverSessionUser.getDataScope();
        //设置一个查询用的代码
        String codeForFind = null;
        switch (dataScope) {
            case "1":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.like(companyTableAlias + ".compCode", codeForFind);
                }
                break;
            case "2":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq(companyTableAlias + ".compCode", codeForFind);
                }
                break;
            default:break;
        }
        return ew;
    }




}
